package luren.king.wechatlite.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONObject;

import luren.king.wechatlite.R;
import luren.king.wechatlite.config.Config;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {
    private EditText emailEditText;
    private EditText passwordEditText;
    private static final String TAG = "彔忈-king";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login);

        // 跳转到注册页
        View registerView = findViewById(R.id.login_tv_register);
        if (registerView != null) {
            registerView.setOnClickListener(v -> {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            });
        }

        emailEditText = findViewById(R.id.login_et_email);
        passwordEditText = findViewById(R.id.login_et_password);
        Switch aSwitch = findViewById(R.id.login_switch_password);
        View loginView = findViewById(R.id.login_button);
        if (loginView != null) {
            loginView.setOnClickListener(v -> {
                try {
                    String email = emailEditText.getText().toString();
                    String password = passwordEditText.getText().toString();
                    if (email.isEmpty() || password.isEmpty()){
                        Toast.makeText(this, "账号或密码为空", Toast.LENGTH_LONG).show();
                        return;
                    }
                    JSONObject user = new JSONObject();
                    user.put("email", email);
                    user.put("password", password);

                    AlertDialog.Builder builder = new AlertDialog.Builder(this);

                    // 加载自定义的布局
                    LayoutInflater inflater = getLayoutInflater();
                    View dialogView = inflater.inflate(R.layout.custom_loading_dialog, null);

                    // 设置自定义背景
                    dialogView.setBackgroundResource(R.drawable.dialog_background);

                    // 设置Dialog的视图
                    builder.setView(dialogView);

                    // 创建并显示AlertDialog
                    AlertDialog alertDialog = builder.create();
                    alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent); // 设置窗口背景透明
                    alertDialog.setCancelable(false); // 禁用取消操作（例如点击外部取消）

                    alertDialog.show();

                    new Thread(){
                        @Override
                        public void run() {
                            Looper.prepare();
                            try {
                                OkHttpClient client = new OkHttpClient().newBuilder()
                                        .build();
                                MediaType mediaType = MediaType.parse("application/json");
                                RequestBody body = RequestBody.Companion.create(user.toString(), mediaType);
                                Request request = new Request.Builder()
                                        .url(Config.DEFAULT_URL + "/web/login")
                                        .method("POST", body)
                                        .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                                        .addHeader("Content-Type", "application/json")
                                        .build();
                                Response response = client.newCall(request).execute();
                                JSONObject json = new JSONObject(response.body().string());
                                runOnUiThread(() -> {
                                    try {
                                        if (json.getInt("code") == 200){
                                            JSONObject data = json.getJSONObject("data");
                                            Config.JWT_TOKEN = data.getString("Token");
                                            if (aSwitch.isChecked()){
                                                //保存密码
                                            }else {
                                                //清空密码
                                            }
                                            alertDialog.dismiss();
                                            Config.EMAIL = email;
                                            Intent intent = new Intent();
                                            intent.setClass(LoginActivity.this, MainActivity.class);
                                            LoginActivity.this.startActivity(intent);
                                            finish();
                                        }else {
                                            alertDialog.dismiss();
                                            Toast.makeText(LoginActivity.this, json.getString("msg"), Toast.LENGTH_LONG).show();
                                        }
                                    } catch (Exception e) {
                                        throw new RuntimeException(e);
                                    }
                                });
                            } catch (Exception e) {
                                Log.e(TAG, "run: " + e);
                                alertDialog.dismiss();
                                Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_LONG).show();
                            }
                            Looper.loop();
                        }
                    }.start();
                } catch (Exception e) {
                    Log.e(TAG, "onCreate: " + e);
                    Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_LONG).show();

                }
            });
        }
    }
}